<template>
    <div class="addBrand-container" id="model-add-app">
        <div class="container">
            <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :inline="true" label-width="180px"
                class="demo-ruleForm">
                <div class="horizontal-div">
                    <!-- 第一个 div -->
                    <el-form-item label="模型名称:" prop="name">
                        <el-input v-model="ruleForm.name" placeholder="请填写模型名称" maxlength="20" />
                    </el-form-item>
                    <el-form-item label="模型分类:" prop="categoryId">
                        <el-select v-model="ruleForm.categoryId" placeholder="请选择模型分类">
                            <el-option v-for="(item, index) in modelList" :key="index" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </div>
                <div class="horizontal-div">
                    <!-- 第二个 div -->
                    <el-form-item label="安卓端模型:" prop="androidModelPath">
                        <el-upload ref="fileUpload" :before-upload="beforeAndroidUpload" v-model="ruleForm.androidModelPath"
                            style="float: left;" action="http://42.192.90.134:81/common/uploadModelForAndroid" directory
                            drag :on-success="handleAndroidSuccess">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将压缩包拖到此处，或<em>点击上传</em></div>
                            <!-- TODO: 下面的文字位置还是有点问题，应该靠左，但是使用float会导致其他的位置错位 -->
                            <div class="el-upload__tip" slot="tip">只接受zip压缩包上传(要求GLB格式)</div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="苹果端模型:" prop="iosModelPath">
                        <el-upload ref="fileUpload" :before-upload="beforeIosUpload" v-model="ruleForm.iosModelPath"
                            style="float: left;" action="http://42.192.90.134:81/common/uploadModelForIOS" directory drag
                            :on-success="handleIosSuccess">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将压缩包拖到此处，或<em>点击上传</em></div>
                            <!-- TODO: 下面的文字位置还是有点问题，应该靠左，但是使用float会导致其他的位置错位 -->
                            <div class="el-upload__tip" slot="tip">只接受zip压缩包上传(要求USDZ格式)</div>
                        </el-upload>
                    </el-form-item>
                </div>
                <div class="horizontal-div">
                    <!-- 第三个 div -->
                    <el-form-item label="模型图片:" prop="region" class="uploadImg">
                        <el-upload class="avatar-uploader" action="http://42.192.90.134:81/common/upload" multiple
                            :show-file-list="true" style="display: flex;width: 100vh;" :on-success="handleAvatarSuccess"
                            list-type="picture-card" :file-list="this.imageUrlList" :limit="this.maxCount"
                            :on-remove="this.handleRemove" :on-exceed="this.handleExceed" :on-change="onChange"
                            ref="upload">
                            <i slot="default" class="el-icon-plus"></i>

                        </el-upload>
                    </el-form-item>
                </div>
                <div class="horizontal-div">
                    <!-- 第四个 div -->
                    <div class="address" style="float: left;">
                        <!-- 其他 div 元素 -->
                        <el-form-item label="模型描述:" prop="region">
                            <el-input v-model="ruleForm.description" type="textarea" :rows="3" placeholder="模型描述，最长200字"
                                maxlength="200" />
                        </el-form-item>
                    </div>
                </div>

                <div class="subBox address">
                    <!-- 其他 div 元素 -->
                    <el-form-item>
                        <el-button @click="goBack()">取消</el-button>
                        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                        <el-button v-if="actionType == 'add'" type="primary" class="continue"
                            @click="submitForm('ruleForm', 'goAnd')">保存并继续添加模型</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import { queryModelById, getCategoryList, addModel, editModel } from '../../api/model'
import { download, upload, uploadModel } from '../../api/common'

export default {
    data() {
        return {
            maxCount: 4,
            id: '',
            restKey: 0,
            textarea: '',
            value: '',
            imageUrl: '',
            imageUrlList: '',
            actionType: '',
            modelList: [],
            modelFlavorsData: [],
            modelFlavors: [],
            vueRest: '1',
            index: 0,
            inputStyle: { 'flex': 1 },
            ruleForm: {
                'name': '',
                'id': '',
                'androidModelPath': '',
                'iosModelPath':'',
                'textures':'',
                'code': '',
                'image': '',
                'description': '',
                'modelFlavors': [],
                'status': true,
                categoryId: ''
            },
        };
    },
    computed: {
        rules() {
            return {
                'name': [
                    { 'required': true, 'message': '请填写模型名称', 'trigger': 'blur' }
                ],
                'categoryId': [
                    { 'required': true, 'message': '请选择模型分类', 'trigger': 'change' }
                ],
                'androidModelPath': [
                    {
                        'required': true,
                        validator: (rule, value, callback) => {
                            if (value && value.length > 0) {
                                callback();
                            } else {
                                callback(new Error('请填写安卓模型数据'));
                            }
                        },
                        trigger: 'change'
                    }
                ],
                'iosModelPath': [
                    {
                        'required': true,
                        validator: (rule, value, callback) => {
                            if (value && value.length > 0) {
                                callback();
                            } else {
                                callback(new Error('请填写苹果模型数据'));
                            }
                        },
                        trigger: 'change'
                    }
                ]
            };
        }
    },
    created() {
        this.getModelList();

        this.id = this.$route.params.id;
        console.log("this.id:" + this.id)
        this.actionType = this.id ? 'edit' : 'add';

        if (this.id) {
            this.init();
        }
    },
    methods: {
        handleRemove(file, fileList) {
            this.imageUrlList.map((item, index) => {
                if (item.uid == file.uid) {
                    this.imageUrlList.splice(index, 1);
                }
            });
            // 将imageUrlList中的url部分提取并用逗号间隔拼接成字符串
            this.ruleForm.image = this.imageUrlList.map(item => item.url).join(',');

        },
        handleExceed() {
            this.$message({
                message: '最多只能上传' + this.maxCount + '张图片',
                type: 'warning',
                duration: 1000
            })
        },
        handleAndroidSuccess(response,file,fileList) {
            // 处理成功逻辑
            console.log("response:"+response)
            console.log("file:"+file.name)

        },
        handleIosSuccess(response,file,fileList) {
            // 处理成功逻辑
            console.log("response:"+response)
            console.log("file:"+file.name)

        },
        handleAvatarSuccess(response, file, fileList) {
            if (response.code === 0 && response.msg === '未登录') {
                window.top.location.href = '/backend/page/login/login.html';
            } else {
                this.imageUrl = `http://42.192.90.134:8082/images/${response.data}`
                // 在这里判断是否已经有值，如果有就加上逗号
                if (this.ruleForm.image) {
                    this.ruleForm.image += `,${this.imageUrl}`;
                } else {
                    this.ruleForm.image = this.imageUrl;
                }
            }
        },
        beforeAndroidUpload(file) {
            const maxSizeBytes = 50 * 1024 * 1024; // 50MB
            if (file.name.toLowerCase().endsWith('.zip')) {
                if (file.size <= maxSizeBytes) {
                    let fileName=file.name
                    this.ruleForm.androidModelPath = fileName.substring(0, fileName.lastIndexOf("."));
                    this.ruleForm.textures=this.ruleForm.androidModelPath
                    return true;
                } else {
                    this.$message.error('文件大小超过限制');
                }
            } else {
                this.$message.error('只允许上传ZIP压缩包');
            }
        },
        beforeIosUpload(file) {
            const maxSizeBytes = 50 * 1024 * 1024; // 50MB
            if (file.name.toLowerCase().endsWith('.zip')) {
                if (file.size <= maxSizeBytes) {
                    let fileName=file.name
                    this.ruleForm.iosModelPath = fileName.substring(0, fileName.lastIndexOf("."));
                    return true;
                } else {
                    this.$message.error('文件大小超过限制');
                }
            } else {
                this.$message.error('只允许上传ZIP压缩包');
            }
        },
        init() {

            queryModelById(this.id).then(res => {
                console.log(res)
                if (String(res.code) === '1') {
                    this.ruleForm = { ...res.data }
                    this.ruleForm.status = res.data.status == '1'
                    // this.modelFlavors = res.data.flavors && res.data.flavors.map(obj => ({ ...obj, value: JSON.parse(obj.value),showOption: false }))
                    // console.log('this.modelFlavors',this.modelFlavors)

                    this.ruleForm.id = this.id
                    console.log("this.ruleForm.id:" + this.ruleForm.id)
                    // TODO:这里看下感觉不知道该不该注释掉，到时候再认真看下
                    // this.ruleForm.id = res.data.data.categoryId


                    // this.imageUrl = res.data.data.image

                    this.imageUrl = res.data.image
                    this.imageUrlList = res.data.imageList.map((item, index) => {
                        return {
                            url: item,
                            name: index
                        };
                    });
                    this.ruleForm.image = res.data.image

                } else {
                    this.$message.error(res.data.msg || '操作失败')
                }
            })
        },
        getModelList() {
            getCategoryList({ 'type': 1 }).then(res => {
                if (res.code === 1) {
                    this.modelList = res.data
                } else {
                    this.$message.error(res.data.msg || '操作失败')
                }
            })
        },
        onChange(file) {
            if (file) {
                const suffix = file.name.split('.')[1];
                const size = file.size / 1024 / 1024 < 2;
                if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                    this.$message.error('上传模型只支持 png、jpeg、jpg 格式！');
                    this.$refs.upload.clearFiles();
                    return false;
                }
                if (!size) {
                    this.$message.error('上传文件大小不能超过 2MB!');
                    return false;
                }
                return file;
            }
        },
        goBack() {
            window.parent.menuHandle({
                id: '/model/list',
                name: '模型管理'
            }, false)
            this.$router.back();
        },
        submitForm(formName, st) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let params = { ...this.ruleForm };
                    params.status = this.ruleForm ? 1 : 0;
                    params.categoryId = this.ruleForm.categoryId;
                    if (!this.imageUrl) {
                        this.$message.error('请上传模型图片');
                        return;
                    }
                    if (this.actionType === 'add') {
                        addModel(params).then(res => {
                            if (res.code === 1) {
                                this.$message.success('模型添加成功！')
                                if (!st) {
                                    this.goBack()
                                } else {
                                    this.modelFlavors = []
                                    // this.modelFlavorsData = []
                                    this.imageUrl = '',
                                        this.imageUrlList = [],
                                        this.ruleForm = {
                                            'name': '',
                                            'id': '',
                                            'androidModelPath': '',
                                            'iosModelPath':'',
                                            'textures':'',
                                            'code': '',
                                            'image': '',
                                            'description': '',
                                            'modelFlavors': [],
                                            'status': true,
                                            categoryId: ''
                                        }
                                }
                            } else {
                                this.$message.error(res.data.msg || '操作失败')
                            }
                        }).catch(err => {
                            this.$message.error('请求出错了：' + err)
                        })
                        //   下面是editModel方法
                    } else {
                        editModel(params).then(res => {
                            if (res.code === 1) {
                                this.$message.success('模型修改成功！')
                                this.goBack()
                            } else {
                                this.$message.error(res.data.msg || '操作失败')
                            }
                        }).catch(err => {
                            this.$message.error('请求出错了：' + err)
                        })
                    }
                } else {
                    return false;
                }
            });
        }
    }
};
</script>

<style scoped>
/* Add your CSS styles here */
.horizontal-div {
    display: flex;
    align-items: center;
    /* 可根据需要调整垂直间距 */
}

.selectInput {
    position: relative;
    width: 100%;
    min-width: 100px;
}

.selectInput .flavorSelect {
    position: absolute;
    width: 100%;
    padding: 0 10px;
    border-radius: 3px;
    border: solid 1px #FF903D;
    line-height: 30px;
    text-align: center;
    background: #fff;
    top: 50px;
    z-index: 99;
}

.selectInput .flavorSelect .items {
    cursor: pointer;
    display: inline-block;
    width: 100%;
    line-height: 35px;
    border-bottom: solid 1px #f4f4f4;
    color: #666;
}

.selectInput .flavorSelect .none {
    font-size: 14px;
}

#model-add-app .uploadImg .el-form-item__label::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}
</style>